<?

require_once("utilities.php");
require_once("mysql.php");
require_once("location.php");
require_once("session.php");


/*
 * OK so this is a promising API from IPINFODB.COM... lets see how well it holds up!
 */
function ipinfodb_geolocate($ip) {

    $APPKEY = "13cc11b44624c8bb4fe10d1e8754b14f0e98f490e772018fc793d62639a588b1";
    $SEARCH = "http://api.ipinfodb.com/v3/ip-city/?key=".$APPKEY."&ip=".$ip."&format=json";
    
    $json = file_get_contents($SEARCH);
    $p = json_decode($json, true);  
    $entry = array('ip'           =>$p['ipAddress'],
                   'country_code' =>strtolower($p['countryCode']),
                   'country'      =>strtolower($p['countryName']),
                   'region'       =>strtolower($p['regionName']),
                   'city'         =>strtolower($p['cityName']),
                   'zip'          =>strtolower($p['zipCode']),
                   'lat'          =>$p['latitude'],
                   'lng'          =>$p['longitude']
                   );
 
    if ($entry['country_code'] == "us") {

        $entry['state'] = us_state_abbr($entry['region']);
    }

    if (empty($entry['lat']) || empty($entry['lng'])) {

        return NULL;

    }

    return $entry;
}


 

function geolocation_find_or_create($ip) {

    $r = MYSQL_Q("SELECT * FROM geolocation WHERE ip='".$ip."'");
    $c = mysql_num_rows($r);

    if ($c == 0) {

        $g = ipinfodb_geolocate($ip);

        if ($g == NULL) die();

        $locstr = NULL;

        if ($g['country_code'] == 'us') {

            $locstr = $g['city'].", ".$g['state'];

        } else {

            $locstr = $g['city'].", ".$g['region'].", ".$g['country'];

        }

        $locstr = strtolower($locstr);

        MYSQL_Q("INSERT INTO geolocation (ip, location) VALUES ('".$ip."', '".ESC($locstr)."')");

        echo json_encode(array('location'=>$locstr));

    } else { 
    
        $row = mysql_fetch_assoc($r);

        MYSQL_Q("UPDATE geolocation SET count=count+1 WHERE ip='".$row['ip']."'");

        $loc = $row['location'];
   
        echo json_encode(array('location'=>$loc));

    }
    
}


SESSION();

geolocation_find_or_create(IP2());

 

?>